// fetch.js
// 用到了中间件的思想，方便对请求做统一处理

import axios from 'axios';
import utils from './utils';

// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

function Fetch(){
  this.chain = [];
  this.index = {};
  // this.index = [];
  // this.indexMap = [];
  // this.isBreak = [];
}
// 添加中间件
Fetch.prototype.use = function(handler){
  if(utils.getType(handler) === 'function'){
    this.chain.push(handler);
  }
}
// 获取每次请求的key，这里使用url，也可以通过其他算法生成
Fetch.prototype.getKey = function(url){
  let key = url;
  // http://www.baidu.com:8080/abc/dev/dfas.do -> dfas
  // let reg = /^https?:\/\/[\w.]+:*[\d]*\/([\w/]*)/;
  let reg = /\/(\w*)\.?\w*$/;
  let regResult = url.match(reg);
  // console.log(regResult,url);
  // debugger;
  if(regResult){
    key = '/' + regResult[1];
  }
  return key;
}
Fetch.prototype.next = function(opts, isBreak){
  // console.log(opts.url, isBreak, this.index);
  let key = this.getKey(opts.url);
  if(!this.index[key]){
    this.index[key] = {
      index: 0,
      isBreak: false
    }
  }
  if(isBreak === 'break'){
    this.index[key].isBreak = true;
    // this.index = 0;
    return;
  }
  if(this.index[key].index >= this.chain.length){
    // this.index[opts.url].index = 0;
    return;
  }
  // console.log(JSON.stringify(this.index));
  let middleware = this.chain[this.index[key].index];
  this.index[key].index++;
  middleware(opts, this.next.bind(this));
}

Fetch.prototype.get = function(options){
  if(!options.data){
    options.data = {};
  }
  if(utils.getType(options) !== 'object' || utils.getType(options.data) !== 'object'){
    throw new Error('fetch参数错误');
  }
  // let opts = JSON.parse(JSON.stringify(options));
  let opts = options;
  this.next(opts, null);
  let key = this.getKey(opts.url);
  if(this.index[key].isBreak){
    delete this.index[key];
    return;
  }

  axios.get(opts.url, {
    params: opts.data
  }).then((res) => {
    // console.log(res);
    opts.success && opts.success(res);
  }).catch((e) => {
    // console.log(e);
    opts.error && opts.error(e);
  })
}

Fetch.prototype.post = function(options){
  if(!options.data){
    options.data = {};
  }
  if(utils.getType(options) !== 'object' || utils.getType(options.data) !== 'object'){
    throw new Error('fetch参数错误');
  }
  // let opts = JSON.parse(JSON.stringify(options));
  let opts = options;
  this.next(opts, null);
  let key = this.getKey(opts.url);

  if(this.index[key].isBreak){
    delete this.index[key];
    return;
  }
  delete this.index[key];
  axios.post(opts.url, opts.data).then((res) => {
    // console.log(res);
    opts.success && opts.success(res);
  }).catch((e) => {
    // console.log(e);
    opts.error && opts.error(e);
  })
}
let fetchInstance = new Fetch();
// fetchInstance.use((req, res, next) => {
//   console.log(req, res);
//   next();
// })
// fetchInstance.next();

export default fetchInstance;
